﻿using AutoMapper;
using MediatR;
using Traceability.App.API.Application.Command.Breeding;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Breeding
{
    /// <summary>
    /// 创建养殖信息内容请求命令处理类
    /// </summary>
    public class CreateBreedingHandler:IRequestHandler<CreateBreedingCommand,ApiResult<int>>
    {
        IBaseRepository<Breeding_Information> breeRep;
        IMapper mapper;

        public CreateBreedingHandler(IBaseRepository<Breeding_Information> breeRep, IMapper mapper)
        {
            this.breeRep = breeRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateBreedingCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var breeding=breeRep.GetAll().Where(x=>x.Production_Batch==request.production_Batch&&!x.IsDeleted).FirstOrDefault();

                if(breeding==null)
                {
                    var model = mapper.Map<Breeding_Information>(request);

                    int r =breeRep.CreateAsync(model).Result;
                    if (r > 0)
                    {
                        res.Msg = "设置成功";
                        res.Code = ApiEnum.Success;
                        res.Data = r;
                    }
                    else
                    {
                        res.Msg = "设置失败";
                        res.Code = ApiEnum.Fail;
                    }
                    return Task.FromResult(res);

                }
                else
                {
                    var model = mapper.Map(request, breeding);

                    int r = breeRep.UpdateAsync(model).Result;
                    if (r > 0)
                    {
                        res.Msg = "设置成功";
                        res.Code = ApiEnum.Success;
                        res.Data = r;
                    }
                    else
                    {
                        res.Msg = "设置失败";
                        res.Code = ApiEnum.Fail;
                    }
                    return Task.FromResult(res);
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
